import { parser } from "posthtml-parser";
import { render } from "posthtml-render";

import { isString, isObject } from "lodash-es";
import { shirkhanToUgProcessor, shirkhanStringify } from "shirkhan-retext";

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message === "shirkhanConvertMenu") {
    $(document).ready(function () {
      function convert(text) {
        return shirkhanToUgProcessor()
          .use(shirkhanStringify)
          .processSync(text)
          .toString();
      }

      /**
       *
       * @param {import("posthtml-parser").Node[]} tree
       */
      function handleTree(tree) {
        if (!tree) return tree;
        return tree.map(function (node) {
          if (isObject(node)) {
            if (node?.tag !== "code") {
              // 不处理code
              node.content = handleTree(node.content);
            }
            return node;
          }
          return convert(node);
        });
      }

      const markdownBody = $(".markdown-body")[0];
      if (markdownBody) {
        $(markdownBody).addClass("shirkhan-markdown-body");
        $(markdownBody)
          .children()
          .each(function (index, elem) {
            const cloneElem = $(this).clone(false);
            $(cloneElem).insertAfter($(this));
            const html = $(cloneElem).html();

            // 转成 html 语法树 来处理文本
            const astTree = parser(html);
            const convertedTree = handleTree(astTree);
            $(cloneElem).html(render(convertedTree));
          });
      } else {
        console.log("没找到markdown body ");
      }
    });
  }
  sendResponse("main content-script 收到了你的消息");
});
